<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Carbon\Carbon;
use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsClass;
use Laminas\Mvc\I18n\Translator;
use Operation\Entity\DiscountRule;
use Operation\Form\DiscountRuleForm;
use Operation\Service\DiscountRuleManager;

/**
 * 优惠促销
 * Class DiscountController
 * @package Operation\Controller
 */
class DiscountController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $discountRuleManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        DiscountRuleManager $discountRuleManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->discountRuleManager = $discountRuleManager;
    }

    /**
     * 促销规则列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $discountRuleList = $this->entityManager->getRepository(DiscountRule::class)->findBy([], ['discountRuleId' => 'DESC']);

        return ['discountRule' => $discountRuleList];
    }

    /**
     * 添加促销规则
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);
        //商品品牌
        $brandList  = $this->goodsPlugin()->goodsBrandOptions('', false);

        $form = new DiscountRuleForm();
        $form->get('goodsBuyType')->setValueOptions([1 => $this->translator->translate('满'), 2 => $this->translator->translate('每')]);
        $form->get('discountMode')->setValueOptions([1 => Common::configValue('default', 'currency')['symbol'], 2 => '%']);
        $form->get('discountUserType')->setValueOptions(['allUser' => $this->translator->translate('所有客户'), 'userGroup' => $this->translator->translate('客户分组')]);
        $form->get('userGroup')->setValueOptions($this->userPlugin()->userGroupOptions('', false));
        $form->get('discountGoodsType')->setValueOptions(['allGoods' => $this->translator->translate('所有商品'), 'goodsClass' => $this->translator->translate('商品分类'), 'goodsBrand' => $this->translator->translate('商品品牌')]);
        $form->get('goodsBrand')->setValueOptions($brandList);
        $form->get('goodsClass')->setValueOptions($this->goodsPlugin()->classValueArray($goodsClass));

        if($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['discountStartTime']))  $data['discountStartTime']  = Carbon::parse($data['discountStartTime'])->timestamp;
                if(!empty($data['discountEndTime']))    $data['discountEndTime']    = Carbon::parse($data['discountEndTime'].' 23:59:59')->timestamp;

                $data['discountUserGroup']  = serialize((!in_array($data['discountUserType'], ['allUser']) ? $data[$data['discountUserType']] : []));
                $data['discountGoodsBody']  = serialize((!in_array($data['discountGoodsType'], ['allGoods']) ? $data[$data['discountGoodsType']] : []));

                $discountRuleInfo = $this->discountRuleManager->addDiscountRule($data);
                $this->createConfig()->createDiscountRule();

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('促销规则 %s 添加成功!'), $discountRuleInfo->getDiscountRuleTitle()), $this->translator->translate('促销'));

                return $this->redirect()->toRoute('operation-discount');
            }
        }

        return [
            'form' => $form,
            'classList' => $classList,
            'brandList' => $brandList,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol']
        ];
    }

    /**
     * 编辑促销规则
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $discountRuleId = (int) $this->params()->fromRoute('id', -1);
        $discountRuleInfo = $this->entityManager->getRepository(DiscountRule::class)->findOneBy(['discountRuleId' => $discountRuleId]);
        if ($discountRuleInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该促销规则不存在!'));
            return $this->redirect()->toRoute('operation-discount');
        }

        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);
        //商品品牌
        $brandList  = $this->goodsPlugin()->goodsBrandOptions('', false);

        $form = new DiscountRuleForm();
        $form->get('goodsBuyType')->setValueOptions([1 => $this->translator->translate('满'), 2 => $this->translator->translate('每')]);
        $form->get('discountMode')->setValueOptions([1 => Common::configValue('default', 'currency')['symbol'], 2 => '%']);
        $form->get('discountUserType')->setValueOptions(['allUser' => $this->translator->translate('所有客户'), 'userGroup' => $this->translator->translate('客户分组')]);
        $form->get('userGroup')->setValueOptions($this->userPlugin()->userGroupOptions('', false));
        $form->get('discountGoodsType')->setValueOptions(['allGoods' => $this->translator->translate('所有商品'), 'goodsClass' => $this->translator->translate('商品分类'), 'goodsBrand' => $this->translator->translate('商品品牌')]);
        $form->get('goodsBrand')->setValueOptions($brandList);
        $form->get('goodsClass')->setValueOptions($this->goodsPlugin()->classValueArray($goodsClass));

        if ($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['discountStartTime']))  $data['discountStartTime']  = Carbon::parse($data['discountStartTime'])->timestamp;
                if(!empty($data['discountEndTime']))    $data['discountEndTime']    = Carbon::parse($data['discountEndTime'].' 23:59:59')->timestamp;

                $data['discountUserGroup']  = serialize((!in_array($data['discountUserType'], ['allUser']) ? $data[$data['discountUserType']] : []));
                $data['discountGoodsBody']  = serialize((!in_array($data['discountGoodsType'], ['allGoods']) ? $data[$data['discountGoodsType']] : []));

                $this->discountRuleManager->editDiscountRule($data, $discountRuleInfo);
                $this->createConfig()->createDiscountRule();

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('促销规则 %s 编辑成功!'), $discountRuleInfo->getDiscountRuleTitle()), $this->translator->translate('促销'));

                return $this->redirect()->toRoute('operation-discount');
            }
        } else {
            $ruleArray = $discountRuleInfo->valuesArray();
            $ruleArray['discountStartTime'] = $ruleArray['discountStartTime'] > 0 ? date("Y-m-d", $ruleArray['discountStartTime']) : '';
            $ruleArray['discountEndTime']   = $ruleArray['discountEndTime'] > 0 ? date("Y-m-d", $ruleArray['discountEndTime']) : '';
            $form->setData($ruleArray);
            if($ruleArray['discountUserType'] == 'userGroup') {
                $form->setData(['userGroup' => unserialize($ruleArray['discountUserGroup'])]);
            }
        }

        return [
            'form' => $form,
            'classList' => $classList,
            'brandList' => $brandList,
            'discountRuleInfo' => $discountRuleInfo,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol']
        ];
    }

    /**
     * 删除促销规则
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $discountRuleId = (int) $this->params()->fromRoute('id', -1);
        $discountRuleInfo = $this->entityManager->getRepository(DiscountRule::class)->findOneBy(['discountRuleId' => $discountRuleId]);
        if ($discountRuleInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该促销规则不存在!'));
            return $this->adminCommon()->toReferer();
        }

        $this->discountRuleManager->deleteDiscountRule($discountRuleInfo);
        $this->createConfig()->createDiscountRule();

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('促销规则 %s 删除成功!'), $discountRuleInfo->getDiscountRuleTitle()), $this->translator->translate('促销'));

        return $this->adminCommon()->toReferer();
    }
}